import React, {FunctionComponent} from "react";
import {connect, useDispatch} from "react-redux";
import {SetLoginInfoAction, AuthLoginByPhoneActions} from "../../store/actions/authAction";
import {Form, Input, Button, Checkbox, message} from "antd";
import {UserOutlined, LockOutlined} from "@ant-design/icons";
import {Post} from "para-lib";
import {REGEXPRULES} from "../../utils/reg";
import {Decrypt, Encrypt} from "../../utils/crypto";
import {AuthInterface} from "../../store/interface/AuthInterface";
import {SettingInterface} from "../../store/interface/SettingInterface";
import {API_CONFIG} from "../../config/api.config";
import "./index.less";

const Logo = require("../../assets/icon.png").default;

export const validatePhoneValue = (_: any, value: string) => {
    if (!value) return Promise.reject(new Error("请输入手机号"));
    if (!REGEXPRULES.phone.test(value) && value !== "sysadmin") return Promise.reject(new Error("手机号格式错误"));
    return Promise.resolve();
};

const Login: FunctionComponent<any> = (props) => {
    const {loginInfo, loading} = props;
    const dispatch = useDispatch();
    const [form] = Form.useForm();
    const [checked, setChecked] = React.useState<boolean>(false);
    const [isRegister, setIsRegister] = React.useState<boolean>(false); // 是否在注册界面

    const onRemember = (event: any) => {
        const check = event.target.checked;
        const password = form.getFieldValue("password");
        const mobile = form.getFieldValue("mobile");
        if (!password || !mobile) {
            message.warn("请输入手机号及密码");
            return;
        }
        setChecked(check);
        if (check) {
            dispatch(SetLoginInfoAction(dispatch, {
                mobile: Encrypt(mobile),
                password: Encrypt(password)
            }));
        } else {
            dispatch(SetLoginInfoAction(dispatch, null));
        }
    };

    const registerFn = async (info: any) => {
        const {err} = await Post({
            url: API_CONFIG.User.register,
            method: "post",
            data: info
        });
        if (err) return;
        message.success("注册成功，请登录");
        setIsRegister(false);
    };


    const onFinish = async (values: any) => {
        if (isRegister) {
            registerFn({
                "username": values.username,
                "password": values.password,
                "phone": values.mobile,
                "email": ""
            });
        } else {
            dispatch(AuthLoginByPhoneActions(dispatch, {
                mobile: Encrypt(values.mobile),
                password: Encrypt(values.password)
            }));
        }
    };

    React.useEffect(() => {
        if (loginInfo) {
            setChecked(true);
            form.setFieldsValue({
                mobile: Decrypt(loginInfo.mobile) || "",
                password: Decrypt(loginInfo.password) || ""
            });
        }
    }, []);

    return (
        <div className={"para-login"}>
            <div className={"para-login-container"}>
                <div className={"para-login-logo"}>
                    <img src={Logo} alt="logo"/>
                    <div className={"para-login-slog"}>
                        <span>Para Low Code</span>
                        <span>低代码平台</span>
                    </div>
                </div>
                <div className={"para-login-box"}>
                    <div className={"para-login-form"}>
                        <h1>{isRegister ? "注册" : "登录"}</h1>
                        <Form name="normal_login" className="login-form" form={form}
                              onFinish={onFinish} validateTrigger={"onChange"} scrollToFirstError>
                            {
                                isRegister && (
                                    <Form.Item name="username"
                                               hasFeedback
                                               rules={[{required: true, message: "请输入用户名!"}]}>
                                        <Input prefix={<UserOutlined className="site-form-item-icon"/>}
                                               placeholder="用户名"/>
                                    </Form.Item>
                                )
                            }
                            <Form.Item name="mobile"
                                       hasFeedback
                                       rules={[{required: true, validator: validatePhoneValue}]}>
                                <Input prefix={<UserOutlined className="site-form-item-icon"/>} placeholder="手机号"/>
                            </Form.Item>
                            <Form.Item name="password"
                                       rules={[{required: true, message: "请输入密码!"}]}>
                                <Input prefix={<LockOutlined className="site-form-item-icon"/>} type="password"
                                       placeholder="密码"/>
                            </Form.Item>

                            <Form.Item>
                                <Form.Item valuePropName="checked" noStyle>
                                    {
                                        !isRegister ? (
                                            <>
                                                <Checkbox onClick={onRemember} checked={checked}>记住密码</Checkbox>
                                                <span className="tip-text">未注册？<span className="active"
                                                                                     onClick={() => setIsRegister(true)}>点击注册</span></span>
                                            </>
                                        ) : (
                                            <>
                                                        <span className="tip-text">已有帐号？<span className="active"
                                                                                              onClick={() => setIsRegister(false)}>点击登录</span></span>
                                            </>
                                        )
                                    }
                                </Form.Item>
                            </Form.Item>

                            <Form.Item>
                                <Button type="primary" htmlType="submit" className="login-form-button"
                                        loading={loading}>{isRegister ? "注册" : "登录"}</Button>
                            </Form.Item>
                        </Form>
                    </div>
                </div>
            </div>
        </div>
    );
};

export default connect(
    (state: { auth: AuthInterface, setting: SettingInterface }) => ({...state.auth, ...state.setting})
)(Login);

